/*
*
* @author Anjana Chatta
*/

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.applet.AudioClip;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.Line;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.AbstractButton;
import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.TransferHandler;
import javax.swing.SwingConstants;

public class ButtonAudioDragDrop extends JPanel {
		    private static final long serialVersionUID = 1L;
			JPanel pan1,pan2;
			JSeparator js;
		    JButton[] buttons;
		    ImageIcon img_blank;
		    ImageIcon img_jpg;
		    URL[] soundURL;
		    Clip clip1,clip2;
			Line line;
			AudioInputStream ais;
			File[] soundfile;
			InputStream[] is;
			AudioClip ac;
			AudioInputStream audioInput;
			BufferedImage img_gray;
			Dimension screenSize;
			int screenHeight;
			int screenWidth;
			MouseHandler mouse;
			ButtonHandlerclass buttonhandler;
			
			//Class Constructor
			public ButtonAudioDragDrop() throws IOException{ 
					super(new BorderLayout());
					
					String[] str_bnames = {"GreetingFriends","ColoringTime","ComputerTime","LibraryTime","LunchTime",
							"MathTime","MusicTime","PaintingTime","PlayTime","PottyTime","ReadingTime","ScienceTime"}; 
					buttons = new JButton[str_bnames.length];
				    pan1 = new JPanel(new GridLayout((str_bnames.length + (str_bnames.length % 2 == 0 ? 0 : 1)) / 2, 4, 5, 5));
					pan2 = new JPanel(new GridLayout((str_bnames.length + (str_bnames.length % 2 == 0 ? 0 : 1)) / 2, 4, 5, 5));
				    
			        buttonhandler= new ButtonHandlerclass();
				    mouse = new MouseHandler();
				    
		            screenSize = Toolkit.getDefaultToolkit().getScreenSize();   //full screen
		    	    screenHeight = screenSize.height;
		    		screenWidth = screenSize.width;
		    		//System.out.println(screenHeight + " " + screenHeight);
		            pan1.setSize(screenWidth / 2, screenHeight);
		            //System.out.println(pan1.getWidth() + " " + pan1.getHeight());
		            pan2.setSize(screenWidth -(pan1.getWidth()), screenHeight);
		            //System.out.println(pan2.getWidth() + " " + pan2.getHeight());
		            pan1.setBackground(Color.YELLOW);
		            pan2.setBackground(Color.green);
					
				    for (int i = 0; i< str_bnames.length; i++)  
			        { 
			            buttons[i] = new JButton(str_bnames[i]);
			            img_jpg = new ImageIcon("src/imgfolder/" + str_bnames[i] + ".jpg"); 
			            buttons[i].setIcon(img_jpg); 
			            buttons[i].setVerticalTextPosition(SwingConstants.BOTTOM); 
						buttons[i].setHorizontalTextPosition(SwingConstants.CENTER);
					    buttons[i].addMouseListener(mouse);
						buttons[i].addMouseMotionListener(mouse);
						buttons[i].setTransferHandler(buttonhandler);
					    pan1.add(buttons[i]);
			        }  
	                for (int i = 0; i< str_bnames.length; i++)  
			        { 
			            buttons[i] = new JButton("Activity Completed");
			            img_blank = new ImageIcon("src/imgfolder/blank.jpg"); 
			            buttons[i].setIcon(img_blank); 
			            buttons[i].setVerticalTextPosition(SwingConstants.BOTTOM); 
						buttons[i].setHorizontalTextPosition(SwingConstants.CENTER);
					    buttons[i].addMouseListener(mouse);
						buttons[i].addMouseMotionListener(mouse);
						buttons[i].setTransferHandler(buttonhandler);
					    pan2.add(buttons[i]);
			        }  
	              
	                add(pan1,BorderLayout.WEST);
	                js = new JSeparator(JSeparator.VERTICAL);
	                js.setBackground(Color.ORANGE.darker().darker());
	                add(js,BorderLayout.CENTER);
	                add(pan2,BorderLayout.EAST);
	                setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
	                
			}//end of constructor
			
			//These are the Mouse Events
	        class MouseHandler implements MouseListener,MouseMotionListener {
	          
	        	private static final long serialVersionUID = 1L;
				//============= Mouse Listener methods
				@Override
				public void mouseClicked(MouseEvent e) {
					// TODO Auto-generated method stub
					Object obj = e.getSource();
	        	    if( obj instanceof JButton) 
	        	    {    
	        	    	  JButton bclicked = (JButton)obj;
		        	      String buttontext = bclicked.getText();
		        	     
						  try {
			    		       audioInput = AudioSystem.getAudioInputStream(ButtonAudioDragDrop.class.getResource("audiofolder/" + buttontext 
			    		    		                                                              + ".WAV"));
			    		      } catch (UnsupportedAudioFileException e3) {
			    						// TODO Auto-generated catch block
			    				e3.printStackTrace();
			    			  } catch (IOException e1) {
									// TODO Auto-generated catch block
								e1.printStackTrace();
							  }
			        	     try {
								clip2 = AudioSystem.getClip();
							  } catch (LineUnavailableException e2) {
								// TODO Auto-generated catch block
								e2.printStackTrace();
							  }
							  
							  try {
								//clip.open(ais);
								clip2.open(audioInput);
							  } catch (LineUnavailableException e1) {
									e1.printStackTrace();
							  } catch (IOException e1) {
									e1.printStackTrace();
							  }
							  if (clip2 != null) {
								   clip2.start();
						      } else{
						             System.out.println("Couldn't load sound");
		        	          }
								  
					}//if
					
				}

				@Override
				public void mouseEntered(MouseEvent e) {
					// TODO Auto-generated method stub
					
				}

				@Override
				public void mouseExited(MouseEvent e) {
					// TODO Auto-generated method stub
				}
				@Override
				public void mousePressed(MouseEvent e) {
					// TODO Auto-generated method stub
				   
				}
               @Override
				public void mouseReleased(MouseEvent e) {
					// TODO Auto-generated method stub
					
				}
                //Mouse Motion Listener methods
			    public void mouseDragged(MouseEvent me) {
				// TODO Auto-generated method stub
				 JComponent comp = (JComponent)me.getSource();
			     TransferHandler hand = comp.getTransferHandler();
			     hand.exportAsDrag(comp, me, TransferHandler.COPY);
			    }
        	    @Override
			    public void mouseMoved(MouseEvent arg0) {
				// TODO Auto-generated method stub
				
			    }
	        }
   	        
	        // Creates new JFrame "Activity Schedule"
		    private static void createAndShowGUI() throws IOException {
				
			    JFrame.setDefaultLookAndFeelDecorated(true);                 //Make sure we have nice window decorations
			    JFrame frame = new JFrame("Activity Schedule");              //Create and set up the window
			    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			    ButtonAudioDragDrop ba= new ButtonAudioDragDrop();     //Create and set up the menu bar and content pane.
			    ba.setOpaque(true);                                    //content panes must be opaque
			    frame.setContentPane(ba);
			    frame.pack();                                          //Display the window.
			    frame.setVisible(true);
		    }//end of createAndShow
			
		    public static void main(String[] args) {
			    //Schedule a job for the event-dispatching thread:
			    //creating and showing this application's GUI.
			    javax.swing.SwingUtilities.invokeLater(new Runnable() 
			    {   public void run() {
			          try {
						createAndShowGUI();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
			        }
			    });
	        }// end of main
		    
		    class ButtonHandlerclass extends TransferHandler implements Transferable {
		   	
                private static final long serialVersionUID = 1L;
				DataFlavor pictureFlavor = DataFlavor.imageFlavor;
				Image sourcePic;                    
				boolean shouldRemove;
				
				//-----------1st Method
				public int getSourceActions(JComponent c) {
				    return TransferHandler.COPY_OR_MOVE;
				  }
                //---------------2nd Method
				public boolean canImport(JComponent c, DataFlavor flavors[]) {          //c is component at the receiving end
					if (c instanceof AbstractButton)                                    //DataFlavor is the type of data to be transfered 
				    {     
						  AbstractButton button = (AbstractButton)c ;
					      Icon icon = button.getIcon();
					      ImageIcon comp_pic = ((ImageIcon) icon);
					      String comp_pic_desc = comp_pic.getDescription();
					      String img_blank_desc = img_blank.getDescription();
					      if (button.isEnabled() && comp_pic_desc == img_blank_desc) 
					      {   
				    	     for (int i = 0; i < flavors.length; i++) {
					             if (pictureFlavor.equals(flavors[i])) {
					                  return true;
					             }
					         }
				          }
				    }
				    return false;
			   }
				//-------------3rd Method
				protected Transferable createTransferable(JComponent c) {            //c is at the source side component
					sourcePic = null;
				    shouldRemove = true;
				    if (c instanceof AbstractButton) 
				    {     AbstractButton button = (AbstractButton)c ;
					      Icon icon = button.getIcon();
					      if (icon instanceof ImageIcon) 
					      {     sourcePic = ((ImageIcon) icon).getImage();
					            return this;
					      }
					 }
					    return null;
				 }
		      
				//--------4th method
			    public boolean importData(JComponent c, Transferable t)               // c is at receiving end
			    {                                                                    // t is the data to be transfered
					if (c instanceof AbstractButton) {
					      AbstractButton button = (AbstractButton) c;
					      if (t.isDataFlavorSupported(pictureFlavor)) {
					        try {
						          sourcePic = (Image)t.getTransferData(pictureFlavor);
						          ImageIcon icon = new ImageIcon(sourcePic);
						          button.setIcon(icon);
						          return true;
					        } catch (UnsupportedFlavorException ignored) {
					        } catch (IOException ignored) {
					        }
					      }
					 }
					shouldRemove = true;
					return false;
					
				 }
		        //Transferable methods
			     public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
							// TODO Auto-generated method stub
			    			if (isDataFlavorSupported(flavor)){
								    return sourcePic;
							}
							return null;
				 }
					
				 public DataFlavor[] getTransferDataFlavors() {
							// TODO Auto-generated method stub
							return  new DataFlavor[] { pictureFlavor };
				 }
		           
				 public boolean isDataFlavorSupported(DataFlavor flavor) {
							// TODO Auto-generated method stub
							return  pictureFlavor.equals(flavor);
				 }
		         protected void exportDone(JComponent c, Transferable t, int action) {      // c is source side component
			    	 if (c instanceof AbstractButton) {
					      AbstractButton button = (AbstractButton) c;
						  try {
							img_gray = ImageIO.read(ButtonAudioDragDrop.class.getResource("imgfolder/Gray.jpg"));
						  } catch (IOException e) {
							e.printStackTrace();
						   } 
		                  if(action == MOVE) {
							   sourcePic = img_gray;
		                	   ImageIcon icon = new ImageIcon(sourcePic);
					           button.setIcon(icon);
					           button.setEnabled(false);
					          
		               	 }
			    	 }
			     }
		 }//end of Button handler class
		
 } //end of class
 
			

		        
